<template>
	<div style="position: relative; padding-top: 15px;">
         <ButtonGroup style='margin-bottom: 15px;'>
	        <Button icon="ios-color-wand-outline" @click="productCate">产品</Button>
	        <Button icon="ios-sunny-outline" @click="informationCate">信息</Button>
	        <Button icon="ios-color-filter-outline" @click="ordersCate">订单</Button>
	    </ButtonGroup>
		
		<!--主要树-->
		<div style="width: 550px;border: #ccc solid 1px;padding: 20px; height: 350px; overflow-X: hidden;" id="treeContent">
			<Tree :data="dataTree" :render="renderContent" ></Tree>
		</div>
		
		<!--查询功能搜索框-->
		<div style="position: absolute;right: 70px;top: 120px; width: 320px;">
			<Input v-model="query">
		        <Select v-model="select" slot="prepend" style="width: 80px">
		            <Option value="1">产品</Option>
		            <Option value="2">信息</Option>
		            <Option value="3">订单</Option>
		        </Select>
		        <Button slot="append" icon="ios-search" @click="queryClick"></Button>
		    </Input>
		</div>
		
		<!--修改与删除-->
		<div style="position: absolute; right: 66px; bottom: 100px;">
			<Button shape="circle" icon="ios-bulb-outline" style="margin-right: 40px;width: 140px;" @click="handleRender">修改选中</Button>
	   		<Button shape="circle" icon="md-build" style="width: 140px;" @click="deletemore">删除多个</Button>
		</div>
		
		<!--确认删除框-->
	    <Modal v-model="modal2" width="360">
	        <p slot="header" style="color:#f60;text-align:center">
	            <Icon type="ios-information-circle"></Icon>
	            <span>删除确认</span>
	        </p>
	        <div style="text-align:center">
	            <p>你确认要删除吗，会同时删除子节点</p>
	        </div>
	        <div slot="footer">
	            <Button type="error" size="large" long  id="delete">删除</Button>
	        </div>
	    </Modal>
	    <Modal v-model="modal3" width="360">
	        <p slot="header" style="color:#f60;text-align:center">
	            <Icon type="ios-information-circle"></Icon>
	            <span>删除确认</span>
	        </p>
	        <div style="text-align:center">
	            <p>你确认要删除吗，会同时删除子节点</p>
	        </div>
	        <div slot="footer">
	            <Button type="error" size="large" long  id="delete2" :loading="modal_loading">删除</Button>
	        </div>
	    </Modal>
	</div>
</template>
<script>
    export default {
        data () {
            return {
            	infoShow:false,
            	modal2: false,
            	modal3:false,
            	modal_loading:false,
            	myUrl:this.GLO.myUrl,
            	select:1,
            	type:1,
            	query:'',
            	xiugai:'',
            	mytreenode:null,
                dataTree: [
                    {
                        title: '产品',
                        expand: true,
                        _id:'5be0fd1667423bed86f586e8',
                        render: (h, { root, node, data }) => {
                            return h('span', {
                                style: {
                                    display: 'inline-block',
                                    width: '100%'
                                }
                            }, [
                                h('span', [
                                    h('Icon', {
                                        props: {
                                            type: 'ios-folder-outline'
                                        },
                                        style: {
                                            marginRight: '8px'
                                        }
                                    }),
                                    h('span', data.title)
                                ]),
                                h('span', {
                                    style: {
                                        display: 'inline-block',
                                        float: 'right',
                                        marginRight: '32px'
                                    }
                                }, [
                                    h('Button', {
                                        props: Object.assign({}, this.buttonProps, {
                                            icon: 'ios-add',
                                            type: 'primary'
                                        }),
                                        style: {
                                            width: '64px'
                                        },
                                        on: {
                                            click: () => { this.append(data) }
                                        }
                                    })
                                ])
                            ]);
                        },
                        children: []
                    }
                ],
                buttonProps: {
                    type: 'default',
                    size: 'small',
                },
                addValue:2
            }
        },
        methods: {
            renderContent (h, { root, node, data }) {
                return h('span', {
                    style: {
                        display: 'inline-block',
                        width: '100%',
                        cursor:'pointer'
                    },
                    'class':{
                    	treenode: true
                    },
                    attrs:{
                    	_id:data._id
                    },
                    on:{
                    	click:(e)=>{
                    		if($(e.target).hasClass('treenode')){
                    			$(e.target).toggleClass('ivu-tree-title-selected')
                    		}else{
                    			$(e.target).parents('.treenode').toggleClass('ivu-tree-title-selected')
                    		}
                    		
                    	}
                    }
                }, [
                    h('span', [
                        h('Icon', {
                            props: {
                                type: 'ios-paper-outline'
                            },
                            style: {
                                marginRight: '8px'
                            }
                        }),
                        h('span', data.title)
                    ]),
                    h('span', {
                        style: {
                            display: 'inline-block',
                            float: 'right',
                            marginRight: '32px'
                        }
                    }, [
                        h('Button', {
                            props: Object.assign({}, this.buttonProps, {
                                icon: 'ios-add'
                            }),
                            style: {
                                marginRight: '8px'
                            },
                            on: {
                                click: (e) => { this.append(data);e.stopPropagation() }
                            }
                        }),
                        h('Button', {
                            props: Object.assign({}, this.buttonProps, {
                                icon: 'ios-remove'
                            }),
                            on: {
                                click: (e) => { this.remove(root, node, data);e.stopPropagation() }
                            }
                        })
                    ])
                ]);
            },
            append (data) {
            	var myid=data._id;
            	var that=this;
                const children = data.children || [];
                children.push({
                    title: '啊洗吧',
                    expand: true,
                    render: (h, { root, node, data }) => {
                            return h('input', {
                                style: {
                                    width: '100px',
                                },
                                on:{
                                	blur:(e)=>{
                                		if(e.target.value){
											$.ajax({
								        		type:"post",
								        		url:this.myUrl+"cate/data",
								        		async:true,
								        		data:{
								        			type:this.type,
								        			parentId:myid,
								        			expand:true,
								        			title:e.target.value
								        		}
								        	}).done(data1=>{
								        		$(e.target).parent().append('<span class="mytree" _id='+data1._id+' style="display: inline-block; width: 100%;cursor:pointer"><span><i class="ivu-icon ivu-icon-ios-paper-outline" style="margin-right: 8px;"></i><span>'
													+e.target.value+
												'</span></span><span style="display: inline-block; float: right; margin-right: 32px;"><button type="button" class="ivu-btn ivu-btn-default ivu-btn-small ivu-btn-icon-only" style="margin-right: 8px;"> <i class="ivu-icon ivu-icon-ios-add"></i> </button><button type="button" class="ivu-btn ivu-btn-default ivu-btn-small ivu-btn-icon-only"><!----> <i class="ivu-icon ivu-icon-ios-remove"></i> <!----></button></span></span>');
								        		data._id=data1._id;
								        		$(e.target).parent().find('.ivu-btn').eq(0).on('click',(e)=>{that.append(data);e.stopPropagation()})
												$(e.target).parent().find('.ivu-btn').eq(1).on('click',(e)=>{that.remove(root, node, data);e.stopPropagation()})
												
												$('.mytree').eq($('.mytree').length-1).on('click',function(e){
								        			$(this).toggleClass('ivu-tree-title-selected');
								        		})
												$(e.target).remove();
								        	})
                                		}else{
                                			this.warning();
                                		}
                                	}
                                }
                            }
                    )}
                });
                this.$set(data, 'children', children);
            },
            remove (root, node, data) {
            	this.modal2=true;
            	var bstop=true;
            	$('.ivu-modal-close').on('click',()=>{
            		this.modal2 = false;
            		bstop=false;
            	});
            	$('.ivu-modal-wrap').on('click',()=>{
            		bstop=false;
            	});
            	
            	$('#delete').on('click',()=>{
            		if(bstop){
            			var parentKey = root.find(el => el === node).parent;
		                var parent = root.find(el => el.nodeKey === parentKey).node;
		                var index = parent.children.indexOf(data);
		                parent.children.splice(index, 1);
		                this.modal2 = false;
		                this.dbDelete(data._id);
		                this.$Message.success('Successfully delete');
            		}
            		bstop=false;
            	})
            },
            productCate(){
            	this.dataTree[0].title='产品';
            	this.type=1;
            	if($('.mytree').length>0){
					this.dataTree[0].expand=false;
	            	setTimeout(()=>{
	            		this.dataTree[0].expand=true;
	            	},200)
				}
            	this.getList(this.type);
            },
            informationCate(){
            	this.dataTree[0].title='信息';
            	this.type=2;
//          	if($('.mytree').length>0){
//          		this.mytreenode=$('.mytree');
//          		$('.mytree').remove();
//          	}
//          	delete this.dataTree[0].children;
//          	console.log(this.dataTree[0].children)
//          	this.dataTree[0].children=[];
//          	console.log(this.dataTree[0].children)
				if($('.mytree').length>0){
					this.dataTree[0].expand=false;
	            	setTimeout(()=>{
	            		this.dataTree[0].expand=true;
	            	},200)
				}
            	this.getList(this.type);
            },
            ordersCate(){
            	this.dataTree[0].title='订单';
            	this.type=3;
            	if($('.mytree').length>0){
					this.dataTree[0].expand=false;
	            	setTimeout(()=>{
	            		this.dataTree[0].expand=true;
	            	},200)
				}
            	this.getList(this.type);
            },
            
            warning (nodesc) {
                this.$Notice.warning({
                    title: '提示',
                    desc: nodesc ? nodesc : '请记得输入分类名称哟~'
                });
            },
            getList(type){
            	$.ajax({
	        		type:"post",
	        		url:this.myUrl+"cate/list/"+type,
	        		async:true
	        	}).done((data)=>{
//	        		this.dataTree=data;
//					$.extend(true, this.dataTree[0].children, data[0].children);
	        		this.dataTree[0].children=data[0].children;
	        		this.dataTree[0]._id=data[0]._id;
	        	})
            },
            dbCreate(myid,title,data1){
            	$.ajax({
	        		type:"post",
	        		url:this.myUrl+"cate/data",
	        		async:true,
	        		data:{
	        			type:this.type,
	        			parentId:myid,
	        			expand:true,
	        			title:title
	        		}
	        	}).done(data=>{
	        		console.log(data1);
	        	})
            },
            dbDelete(id){
            	$.ajax({
	        		type:"delete",
	        		url:this.myUrl+"cate/data/"+id,
	        		async:true
	        	})
            },
            deletemore(){
            	this.modal3=true;
            	var arr=[];
            	$('.ivu-tree-title-selected').each(function(index,ele){
            		arr.push($(ele).attr('_id'));
            	})
            	$('#delete2').on('click',()=>{
            		this.modal_loading=true;
            		try {
            			$.ajax({
			        		type:"post",
			        		url:this.myUrl+"cate/removemore/"+arr.toString(),
			        		async:true
			        	})
            		}catch(e){
            			console.log(e);
            		}finally{
            			setTimeout(()=>{
            				this.modal_loading=false;
            				this.modal3=false;
					        $('.ivu-tree-title-selected').each((index,ele)=>{
					        	$(ele).remove();
					        });
					        this.getList(this.type);
            			},500);
            		}
            	})
            },
            queryClick(){
            	var that=this;
            	$('.ivu-icon-ios-paper-outline').each(function(value,ele){
            		var reg=new RegExp(that.query,'g');
            		if(!that.query){
            			$('.treenode').removeClass('ivu-tree-title-selected');
            			$('.mytree').removeClass('ivu-tree-title-selected');
            		}else if(reg.test($(ele).siblings('span').html())){
            			$(ele).parents('.treenode').addClass('ivu-tree-title-selected');
            			$(ele).parents('.mytree').addClass('ivu-tree-title-selected');
            		}
            	})
            },
             handleRender () {
             	var xz=$('.ivu-tree-title-selected');
             	var myid=xz.attr('_id');
             	console.log(myid)
             	if(xz.length>0 && (xz.hasClass('treenode') || xz.hasClass('mytree'))){
             		var mytext=$('.ivu-tree-title-selected').find('.ivu-icon-ios-paper-outline').siblings('span');
             		
             		this.xiugai=mytext.html();
             		var mm=this.xiugai;
       
             		this.$Modal.confirm({
             			title:'修改分类名称',
             			onOk:()=>{
             				$.ajax({
             					type:"put",
             					url:this.myUrl+"cate/data/"+myid,
             					async:true,
             					data:{
             						title:this.xiugai
             					}
             				}).done((data1)=>{
             					$.ajax({
					        		type:"post",
					        		url:this.myUrl+"cate/list/"+this.type,
					        		async:true
					        	}).done((data1)=>{
				//	        		this.dataTree=data1;
					        		this.dataTree[0].children=data1[0].children;
					        		this.dataTree[0]._id=data1[0]._id;
					        		if($('.ivu-tree-title-selected').hasClass('mytree')){
										this.dataTree[0].expand=false;
						            	setTimeout(()=>{
						            		this.dataTree[0].expand=true;
						            	},200)
									}
					        	})
             				});
                       },
	                    render: (h) => {
	                        return h('Input', {
	                            props: {
	                                value: mm,
	                                autofocus: true,
	                                placeholder: 'Please enter your name...'
	                            },
	                            style:{
	                            	marginTop:'15px'
	                            },
	                            on: {
	                                input: (val) => {
	                                    this.xiugai = val;
	                                }
	                            }
	                        })
	                    }
	                })
             	}else{
             		this.warning('请选中一个分类节点哟~')
             	}
                
            }
        },
        mounted(){
        	this.getList(1);
        },
        
        watch:{
        	select(newValue,oldValue){
        		if(newValue==1){
        			this.productCate();
        		}
        		else if(newValue==2){
        			this.informationCate();
        		}
        		else if(newValue==3){
        			this.ordersCate();
        		}
        	}
        }
    }
</script>

<style type="text/css">
	.ivu-tree-title-selected{
		background-image: linear-gradient(to left,#fff,#d5e8fc);
		position: relative; transform-style: preserve-3d;
		border-radius: 5px;
	}
	.ivu-tree-title-selected:before{
		content: "";  position: absolute; left: -28px; top: 5px;
		border: 6px transparent solid; border-left-color:#999 ;
		animation: ssr 0.7s infinite alternate;
	}
	@keyframes ssr{
		from{transform: translateX(0px);}
		to{transform: translate(2px);}
	}
</style>